﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using log4net;
using NHibernate;
using NHibernate.Criterion;
using TeamCommunitySolution.Domain.DataLayer.Base;
using System.Data.SqlClient;
using TeamCommunitySolution.Services.Factories;

namespace TeamCommunitySolution.Services.Repositories.Impl
{
    public class TeamRepository : ITeamRepository
    {
        /// <summary>
        /// Logger instance.
        /// </summary>
        private static readonly ILog _log = LogManager.GetLogger(typeof(TeamRepository));

        /// <summary>
        /// Repository instance.
        /// </summary>
        private static ITeamRepository _repo = null;

        /// <summary>
        /// Prevents a default instance of the <see cref="TeamRepository"/> class from being created. 
        /// Initializes a new instance of the <see cref="TeamRepository"/> class.
        /// </summary>
        private TeamRepository()
        {
        }

        /// <summary>
        /// Gets the instance.
        /// </summary>
        /// <value>The instance.</value>
        public static ITeamRepository Instance
        {
            get
            {
                if (_repo == null)
                {
                    _repo = new TeamRepository();
                }

                return _repo;
            }
        }

        #region "Team Operations"
        /// <summary>
        /// Gets the team.
        /// </summary>
        /// <param name="id">The team id.</param>
        /// <returns>Instance of the team.</returns>
        public Team GetTeam(string id)
        {
            using (ISession session = NHSessionFactory.Factory.OpenSession())
            {
                try
                {
                    return session.Get<Team>(id);
                }
                catch (SqlException ex)
                {
                    string message = "Unable to find object [team] in datastore";
                    this.HandleException(message, ex);
                }
            }
            return null;
        }

        /// <summary>
        /// Gets the team by field.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="fieldValue">The field value.</param>
        /// <returns>Team instance.</returns>
        public Team GetTeamByField(string field, string fieldValue)
        {
            using (ISession session = NHSessionFactory.Factory.OpenSession())
            {
                ICriteria crit = session.CreateCriteria(typeof(Team));
                crit.Add(Expression.Eq(field, fieldValue));

                IList<Team> results = crit.List<Team>();

                if (results.Count > 1)
                {
                    throw new TeamRepositoryException(string.Format("Duplicate objects [Team] found in the datastore. Field: {0}, Value: {1}", field, fieldValue));
                }

                if (results.Count == 0)
                {
                    return null;
                }

                return results[0];
            }
        }

        /// <summary>
        /// Gets the team request by id.
        /// </summary>
        /// <param name="id">The request id.</param>
        /// <returns>The team request instance.</returns>
        public TeamInvite GetTeamRequestById(string id)
        {
            using (ISession session = NHSessionFactory.Factory.OpenSession())
            {
                try
                {
                    return session.Get<TeamInvite>(id);
                }
                catch (SqlException ex)
                {
                    string message = "Unable to find object [team request] in datastore";
                    this.HandleException(message, ex);
                }
            }
            return null;
        }

        /// <summary>
        /// Saves the team.
        /// </summary>
        /// <param name="team">The team object.</param>
        public void SaveTeam(Team team)
        {
            using (ISession session = NHSessionFactory.Factory.OpenSession())
            {
                try
                {
                    session.SaveOrUpdate(team);
                }
                catch (SqlException ex)
                {
                    string message = "Unable to save object [team] in datastore";
                    this.HandleException(message, ex);
                }
            }
        }
        #endregion

        /// <summary>
        /// Handles the exception.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="ex">The exception.</param>
        private void HandleException(string message, Exception ex)
        {
            _log.Error(message, ex);
            throw new TeamRepositoryException(message, ex);
        }
    }
}